<template>
  <div>
    <!-- 商品上架 -->
    <div class="box">
      <h1>商品介绍</h1>
      <div class="head">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="商品编号" prop="goodsSn">
            <el-input v-model="ruleForm.goodsSn"></el-input>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="市场售价">
            <el-input placeholder="请输入内容" v-model="ruleForm.counterPrice">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否新品">
            <el-radio-group v-model="ruleForm.isNew">
              <el-radio :label="true" value="新品">新品</el-radio>
              <el-radio :label="false" value="非新品">非新品</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否热卖">
            <el-radio-group v-model="ruleForm.isHot">
              <el-radio :label="false" :value="false">普通</el-radio>
              <el-radio :label="true" :value="true">热卖</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否在售">
            <el-radio-group v-model="ruleForm.isOnSale">
              <el-radio :label="true" :value="true">在售</el-radio>
              <el-radio :label="false" :value="false">未售</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              class="avatar-uploader"
              action="http://admin.bsmall.byesame.com/admin/storage/create"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="宣传画廊">
            <el-upload
              action="http://admin.bsmall.byesame.com/admin/storage/create"
              :headers="headers"
              list-type="picture-card"
              :on-success="handlePictureCardPreview"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位">
            <el-input v-model="ruleForm.unit"></el-input>
          </el-form-item>

          <el-form-item label="关键字">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="keywords"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="showInput"
              >增加</el-button
            >
          </el-form-item>
          <el-form-item label="所属分类">
            <el-cascader
              v-model="subcategory"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="所属品牌商">
            <el-select v-model="ruleForm.brandId" placeholder="请选择">
              <el-option
                v-for="item in optioned"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品简介">
            <el-input v-model="ruleForm.brief"></el-input>
          </el-form-item>
          <el-form-item label="商品单位">
            <editor v-model="ruleForm.detail" :init="editorInit" />
          </el-form-item>
          
        </el-form>
      </div>
    </div>
    <div class="banner-box">
      <h1>商品规格</h1>
      <div class="banner-head">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="默认标准规格" name="first">
            <el-table :data="specifications" style="width: 100%">
              <el-table-column prop="specification" label="规格名" width="420">
              </el-table-column>
              <el-table-column prop="value" label="规格值" width="420">
                <template v-slot="scope">
                  <el-tag>{{ scope.row.value }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="picUrl" label="规格图片">
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="多规格支持" name="second">
            <el-table :data="specifications" style="width: 100%">
              <el-table-column prop="specification" label="规格名" width="350">
              </el-table-column>
              <el-table-column prop="value" label="规格值" width="350">
                <template v-slot="scope">
                  <el-tag>{{ scope.row.value }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="picUrl" label="规格图片">
                <template v-slot="scope">
                  <img :src="scope.row.picUrl" alt="" v-if="scope.row.picUrl" />
                </template>
              </el-table-column>
              <el-table-column prop="address" label="操作">
                <template v-slot="scope">
                  <el-button type="danger" icon="el-icon-delete" @click="specificationsDel(scope.row.specification)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-button
          v
          class="button-add"
          size="small"
          type="primary"
          plain
          v-if="isOk"
          @click="addTab"
        >
          增加
        </el-button>
      </div>
    </div>
    <div class="body-box">
      <h1>商品库存</h1>
      <div class="body-head">
        <el-table :data="products" style="width: 100%">
          <el-table-column label="货品规格" width="680">
            <template v-slot="scope">
              <el-tag
                v-for="(item, index) in scope.row.specifications"
                :key="index"
                >{{ item }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="price" label="货品售价" width="150">
          </el-table-column>
          <el-table-column prop="number" width="150" label="货品数量">
          </el-table-column>
          <el-table-column width="150" label="货品图片">
            <template v-slot="scope">
              <img :src="scope.row.url" alt="" v-if="scope.row.url"  />
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template>
              <el-button type="primary" @click="inventorySettings"
                >设置</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="foot-box">
      <h1>商品参数</h1>
      <el-button type="primary" @click="argumentAdd">添加</el-button>
      <div class="foot-head">
        <el-table :data="attributes" style="width: 100%">
          <el-table-column prop="attribute" label="商品参数名称" width="570">
          </el-table-column>
          <el-table-column prop="value" label="商品参数值" width="570">
          </el-table-column>
          <el-table-column prop="address" label="操作">
              <template v-slot="scope">
                <el-button type="danger" icon="el-icon-delete" @click="argumentDel(scope.row.attribute)" >删除</el-button>
              </template>  
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="popUp">
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <span>
          <div class="popUp-box" v-if="title == '设置规格'">
            <div>
              <span>规格名</span>
              <el-input v-model="specificationName"></el-input>
            </div>
            <div>
              <span>规格值</span>
              <el-input v-model="specificationData"></el-input>
            </div>
            <div>
              <span>规格图片</span>
              <el-upload
                class="avatar-uploader"
                action="http://admin.bsmall.byesame.com/admin/storage/create"
                :headers="headers"
                :show-file-list="false"
                :on-success="specificationhandleAvatarSuccess"
                :before-upload="specificationbeforeAvatarUpload"
              >
                <img
                  v-if="imageUrl"
                  :src="specificationimageUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
          <div class="popUp-box" v-if="title == '添加货品'">
            <div>
              <span>货品规格列</span>
              <div>
                <el-tag
                  v-for="(item, index) in products[0].specifications"
                  :key="index"
                  >{{ item }}</el-tag
                >
              </div>
            </div>
            <div>
              <span>货品售价</span>
              <el-input v-model="products[0].price"></el-input>
            </div>
            <div>
              <span>货品数量</span>
              <el-input v-model="products[0].number"></el-input>
            </div>
            <div>
              <span>货品图片</span>
              <el-upload
                class="avatar-uploader"
                action="http://admin.bsmall.byesame.com/admin/storage/create"
                :headers="headers"
                :show-file-list="false"
                :on-success="inventoryhandleAvatarSuccess"
                :before-upload="inventorybeforeAvatarUpload"
              >
                <img v-if="inventoryImg" :src="inventoryImg" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
          <div class="popUp-box" v-if="title == '添加商品参数'" >
            <div>
              <span>商品参数名称</span>
              <el-input v-model="argumentName"></el-input>
            </div>
            <div>
              <span>商品参数值</span>
              <el-input v-model="argumentData"></el-input>
            </div>
          </div>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            v-if="title == '设置规格'"
            @click="specification"
            >确 定</el-button
          >
          <el-button
            type="primary"
            v-if="title == '添加货品'"
            @click="inventory"
            >确 定</el-button
          >
          <el-button
            type="primary"
            v-if="title == '添加商品参数'"
            @click="argument"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
    <div class="head">
      <el-button @click="Cancel" >取消</el-button>
  <el-button type="primary" @click="listing">上架</el-button>
    </div>
  </div>
</template>

<script>
import { listCatAndBrand ,publishGoods } from "../../api/goods";
import Editor from "@tinymce/tinymce-vue";
import BackToTop from "@/components/BackToTop";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import _ from "lodash";
import { createStorage } from "@/api/storage";

import { getToken } from "@/utils/auth";
import { title } from "echarts/lib/theme/dark";

export default {
  // name: "后台Create",
  components: { BackToTop, Pagination, Editor },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
  },

  data() {
    return {
      dialogVisible: false,
      activeName: "first",
      selectTable: [],
      optioned: [],
      isOk: false,
      ruleForm: {
        goodsSn: "",
        name: "",
        isHot: false,
        unit: "",
        isNew: true,
        brandId: "",
        isOnSale: true,
        categoryId: "",
        brief: "",
        detail: "",
      },
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          
        ],
        goodsSn: [
          { required: true, message: "商品编号不能为空", trigger: "blur" },
        ],
       
      },
      options: [],
      dialogImageUrl: [],
      dialogVisible: false,
      dynamicTags: [],
      inputVisible: false,
      keywords: "",
      subcategory: "",
      // editorInit:''
      editorInit: {
        language: "zh_CN",
        height: 200,
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        },
      },
      productTableData: [{}],
      productTableDatas: [],
      imageUrl: "",
      imgUrl: "",
      specifications: [
        {
          value: "标准",
          specification: "规格",
          picUrl: "",
        },
      ],
      title: "",
      specificationimageUrl: "",
      specificationName: "",
      specificationData: "",
      products: [
        {
          id: 0,
          specifications: ["标准"],
          number: 0,
          price: 0,
          url: "",
        },
      ],
      specificationDatas: [],
      inventoryImg: "",
      attributes: [],
      argumentName: '',
      argumentData: '',
    };
  },

  mounted() {},
  created() {
    listCatAndBrand().then((res) => {
      // console.log(res, "选择数据");
      this.options = res.data.data.categoryList;
      this.optioned = res.data.data.brandList;
    });
  },
  methods: {
    // 点击上架
    listing(){
     
      
      let goods = {
        gallery:this.dialogImageUrl,
        picUrl : this.imgUrl,
        ...this.ruleForm
      }
      // console.log(goods);
      publishGoods({
        goods,
        products: this.products,
        specifications: this.specifications,
        attributes: this.attributes
      }).then(res => {
        // console.log(res);
        if (res.data.errmsg == "成功") {
          this.$router.push({
            path: "./list"
          })
        }
      })

      
    },
    // 点击取消
    Cancel() {
      this.$router.push({
        path: "./list"
      })
    },
    // 商品规格删除
    specificationsDel(e) {
      for(var i in this.specifications) {
          if (e == this.specifications[i].specification) {
            this.specifications.splice(i , 1)
          }
        }
    },
    // 商品参数删除
    argumentDel(e) {
        for(var i in this.attributes) {
          if (e == this.attributes[i].attribute) {
            this.attributes.splice(i , 1)
          }
        }
    },
    // 商品参数确定
    argument() {
      this.dialogVisible = false;
      this.attributes.push({
        attribute: this.argumentName,
        value : this.argumentData
      })

    },
    // 商品参数添加
    argumentAdd() {
      this.dialogVisible = true;
      this.title = "添加商品参数";
      this.argumentName = ''
      this.argumentData = ''
    },
    // 库存确定
    inventory() {
      this.dialogVisible = false;
      // console.log(this.products);
      this.products[0].url = this.inventoryImg;
    },
    // 库存上传图片
    inventoryhandleAvatarSuccess(res, file) {
      // this.specificationimageUrl = URL.createObjectURL(file.raw);
      this.inventoryImg = res.data.url;
    },
    inventorybeforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // console.log(this.imageUrl);

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 库存设置
    inventorySettings() {
      this.dialogVisible = true;
      this.title = "添加货品";
    },
    // 新增
    addTab() {
      this.dialogVisible = true;
      this.title = "设置规格";
      this.specificationData = "";
      this.specificationName = "";
      this.specificationimageUrl = "";
    },
    // 规格确定
    specification() {
      this.dialogVisible = false;

      this.specifications.push({
        value: this.specificationData,
        specification: this.specificationName,
        picUrl: this.specificationimageUrl,
      });

      this.specificationDatas.push(this.specificationData);
      this.products = [
        {
          id: this.products.length - 1,
          specifications: this.specificationDatas,
          number: 0,
          price: 0,
          url: "",
        },
      ];
      // console.log(this.specificationData);
      // console.log(this.specificationDatas);
    },
    // 规格图片
    specificationhandleAvatarSuccess(res, file) {
      this.specificationimageUrl = URL.createObjectURL(file.raw);
      this.specificationimageUrl = res.data.url;
    },
    specificationbeforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // console.log(this.imageUrl);

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 弹窗关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 宣传画廊
    handleRemove(file, fileList) {
      // console.log(file, fileList, "aaaaa");
    },
    handlePictureCardPreview(res, file) {
      // console.log("aasdasd");

      // console.log(res ,file , 'aa');

      this.dialogImageUrl.push(res.data.url);
      // this.dialogVisible = true;
    },
    // 商品图片
    handleAvatarSuccess(res, file) {
      // console.log(res, this.imageUrl, file);
      this.imgUrl = res.data.url;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // console.log(this.imageUrl);

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 商品规格
    handleClick(tab, event) {
      // console.log(tab, event, "aa");
      if (tab.paneName == "first") {
        // console.log("aaa");
        this.isOk = false;

        this.specifications = [
          {
            value: "标准",
            specification: "规格",
            picUrl: "",
          },
        ];
        this.products = [
          {
            id: this.products.length - 1,
            specifications: this.specifications[0].value,
            number: 0,
            price: 0,
            url: "",
          },
        ];
      } else {
        this.isOk = true;
        this.specifications = [];
      }
    },
    // 所属分类
    handleChange(value) {
      // console.log(value, "所属分类");
      this.ruleForm.categoryId = value[1];
    },
    // 关键字
    handleClose(tag) {
      // console.log(tag);

      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      // console.log(this.dynamicTags);

      let keywords = this.keywords;
      if (keywords) {
        this.dynamicTags.push(keywords);
      }
      this.inputVisible = false;
      this.keywords = "";
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
.head {
  margin-left: 35px;
}
.foot-box {
  margin: 10px auto;
  width: 95%;
  box-shadow: 0 0 16px 5px #d3d3d3;
  padding: 40px;
}
.body-box {
  margin: 10px auto;
  width: 95%;
  box-shadow: 0 0 16px 5px #d3d3d3;
  padding: 40px;
}
.body-box img {
  width: 40px;
  height: 40px;
}
.banner-box img {
  width: 40px;
  height: 40px;
}
.popUp-box {
  display: flex;
  flex-direction: column;
}
.popUp-box > div {
  width: 70%;
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: center;
  margin: 15px 0;
}
.popUp-box > div:last-child {
  align-items: start;
}
.popUp-box > div > span {
  display: block;
  width: 160px;
  font-size: 18px;
  font-weight: 550;
  margin-left: 40px;
}
::v-deep .avatar-uploader-icon[data-v-2ab64f22] {
  border: 1px dashed #c0ccda !important ;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 148px;
  height: 148px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.banner-head > .button-add {
  position: absolute;
  top: 0;
  left: 500px;
}
.banner-head {
  position: relative;
}
::v-deep .el-tabs__item.is-active {
  background-color: #1890ff;
  color: #fff;
}
::v-deep .el-tabs--card > .el-tabs__header .el-tabs__nav {
  border-bottom: 1px solid #dfe4ed;
}
::v-deep .el-tabs--card > .el-tabs__header {
  border-bottom: none;
}
.banner-box {
  margin: 10px auto;
  width: 95%;
  box-shadow: 0 0 16px 5px #d3d3d3;
  padding: 40px;
}
.box {
  // position: absolute;
  // left: 50%;
  // top: 50%;
  // transform: translate(-50%, -50%);
  margin: 30px auto;
  width: 95%;
  box-shadow: 0 0 16px 5px #d3d3d3;
  padding: 40px;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>